W16. Amortized Analysis
1. Theory
1.1 Why Amortized Analysis Is Needed
1.1.1 Cost of a Sequence
Many data structures have operations whose individual worst-case costs look scary, even though long valid sequences of operations are cheap overall. Amortized analysis is the method used to explain this situation rigorously.
The key idea is to analyze a sequence of operations, not a single operation in isolation. A single operation may cost
This is a worst-case guarantee over sequences. It is not the same as probabilistic average-case analysis. Average-case analysis assumes a probability distribution over inputs or operation choices. Amortized analysis makes no such assumption: it says that every legal sequence of
1.1.2 Stack with Multi-Pop
Consider a stack supporting three operations:
pushes value onto the stack; removes the top value; removes up to the top values.
The worst-case cost of one
A naive worst-case-per-operation argument would say that
This example captures the spirit of amortized analysis: expensive operations spend work that was made possible by earlier cheap operations.
1.2 Aggregate Analysis
1.2.1 Method
Aggregate analysis is the simplest amortized-analysis technique. Instead of assigning different charges to different operation types, it directly bounds the total running time of any sequence of
The method has two steps:
- Prove that every valid sequence of
operations has total actual cost at most . - Divide by
to obtain an amortized cost per operation:
The symbol
Aggregate analysis is easy to understand, but it can be too coarse. It gives one common amortized bound for all operations, even when different operation types have different natural costs.
1.2.2 Binary Counter
A standard example is a binary counter stored as a bit array
INCREMENT(A, k)
1 i = 0
2 while i < k and A[i] == 1
3 A[i] = 0
4 i = i + 1
5 if i < k
6 A[i] = 1
One increment may flip many bits. For example,
However, over many increments, low-order bits flip much more often than high-order bits. Bit
So the total cost of
1.3 Accounting Method
1.3.1 Credits
The accounting method assigns each operation an amortized cost
If
Formally, for every prefix of the operation sequence,
for all
1.3.2 Stack Credits
For the stack with
| Operation | Actual cost | Amortized cost |
|---|---|---|
| number of removed elements |
Each push pays
This proves
1.3.3 Binary Counter Credits
For the binary counter, charge
When a bit changes from
An increment changes at most one bit from
1.4 Potential Method
1.4.1 Potential Functions
The potential method is a mathematical version of the accounting method. Instead of placing explicit credits on individual objects, it defines a nonnegative stored energy for the whole data structure.
Let
If the potential increases, the operation is charged extra and stores energy for the future. If the potential decreases, the operation uses stored energy to pay for actual work.
To make the bound valid, the potential must satisfy
for every
So the total amortized cost upper-bounds the total actual cost.
1.4.2 Stack Potential
For the stack, choose
This potential is always nonnegative. A push costs
This is the same intuition as the accounting method: each stack element represents one unit of stored future removal work.
1.4.3 Binary Counter Potential
For the binary counter, choose
Suppose an increment changes
Therefore
Again the amortized cost is constant. Long carry chains are paid for by the potential stored in the trailing
1.5 Dynamic Tables
1.5.1 Expansion Only
A dynamic array stores elements in a contiguous table with some capacity
A single append may cost
This potential is useful when the table is at least half full after initialization and resizing. It grows by
The result is
1.5.2 Expansion and Contraction
If the table also supports
The load factor is
With doubling at
The potential is zero near
1.6 More Amortized Data Structures
1.6.1 Queue from Two Stacks
A queue can be implemented using two stacks. Let
pushes onto . pops from if is nonempty.- If
is empty, move all elements from to by popping them from and pushing them onto , then pop from .
The transfer reverses the order, so the oldest enqueued element becomes the top of
The amortized analysis is simple: each enqueued element will be pushed once into
1.6.2 Union by Smaller Set
Suppose a set data structure supports
in time
The total movement over all unions is
1.6.3 Periodic Rebalancing
Some data structures perform occasional global repairs. For example, a binary search tree might insert normally and then rebalance after enough insertions have accumulated. The accounting method handles this by charging each insertion extra credit and saving that credit for the next full rebuild.
The central design question is not whether rebuilding is expensive; it is whether enough cheap operations must occur between rebuilds to pay for it. If a tree of size
2. Definitions
- Amortized analysis: A worst-case analysis of the average cost per operation over every valid sequence of operations.
- Actual cost
: The real cost paid by the -th operation. - Amortized cost
: The artificial cost assigned to the -th operation for analysis. - Aggregate analysis: A method that bounds total cost
for operations and divides by . - Accounting method: A method that overcharges some operations and stores the surplus as credit for later expensive operations.
- Credit: Stored prepaid work used to pay for future actual cost.
- Prefix condition: The requirement that total amortized cost is at least total actual cost for every prefix of the sequence.
- Potential method: A method that represents stored prepaid work by a function of the data-structure state.
- Potential function
: A function assigning stored energy or credit to a data-structure state. - State
: The data structure after the -th operation. - Binary counter: A bit-array representation of an integer where increment may flip trailing
bits to and one bit to . - Trailing 1s: Consecutive
bits at the low-order end of a binary counter. - Dynamic array: An array-backed sequence that resizes when capacity becomes insufficient.
- Capacity
: The number of elements that can fit in the currently allocated table. - Load factor
: The ratio of stored elements to capacity. - Hysteresis: Using different thresholds for expansion and contraction to avoid repeated resizing.
- Queue from two stacks: A FIFO queue implementation that uses one stack for incoming elements and one stack for outgoing elements.
- Union by smaller set: A union strategy that always moves or relabels elements of the smaller set.
- Periodic rebalancing: Occasional global rebuilding paid for by credit accumulated during ordinary operations.
3. Formulas
- Aggregate amortized cost:
- Accounting prefix condition:
for every - Potential amortized cost:
- Potential validity condition:
for every - Binary-counter aggregate flips:
- Stack potential:
- Binary-counter potential:
- Expansion-only dynamic-array potential:
- Expansion-contraction table potential:
- Union-by-smaller-set movement bound:
moves per element
4. Practice
4.1. Analyze Multi-Pop Stack by Aggregate Analysis (Lecture 14, Example 1)
Using aggregate analysis, analyze the total running time of a sequence of
Click to see the solution
Key Concept: A popped element must previously have been pushed, and each pushed element can be popped at most once.
First consider the loose bound. In one operation,
This bound is valid but not tight.
For the tight aggregate analysis, count element movements instead:
- Each
inserts one element and costs . - Each element inserted by a push can be removed only once.
- A removal may happen through
or as one of the removals inside . - Since the sequence has at most
pushes, at most elements can ever be removed.
Therefore the total cost of all pushes is at most
Dividing by the number of operations gives
Answer: Any sequence of
4.2. Analyze Binary Counter by Aggregate Analysis (Lecture 14, Example 2)
Use aggregate analysis to analyze the cost of incrementing a binary counter stored as a bit array.
Click to see the solution
Key Concept: Bit
Let
- bit
flips on every increment, so at most times; - bit
flips every increments, so at most times; - bit
flips every increments, so at most times; - in general, bit
flips at most times.
Thus the total number of flips is at most
The geometric series satisfies
Therefore
The amortized cost per increment is
Answer: A sequence of
4.3. Analyze Multi-Pop Stack by the Accounting Method (Lecture 14, Example 3)
Analyze a sequence of
Click to see the solution
Key Concept: Store one credit on each pushed element, and use that credit when the element is removed.
Assign amortized costs as follows:
| Operation | Actual cost | Amortized cost |
|---|---|---|
| number of removed elements |
When
The first unit pays for the actual push. The second unit is stored as credit on the new stack element.
Now consider any future removal. If an element is removed by
The credit balance can never become negative because the data structure never removes an element that was not previously pushed. Each removal consumes the credit of exactly one existing element.
Thus every operation has amortized cost at most
Answer: Charge
4.4. Analyze Binary Counter by the Accounting Method (Lecture 14, Example 4)
Use the accounting method to analyze a sequence of INCREMENT operations on a binary counter stored as a bit array.
Click to see the solution
Key Concept: A bit that is set to
During one increment, some number
Use this charging scheme:
- charge
for a flip ; - charge
for a flip .
When a bit flips from
Now check a whole increment. It may reset
So the amortized cost of one increment is at most
The credit balance is always nonnegative because only bits currently equal to
Answer: Charge
4.5. Analyze Multi-Pop Stack by the Potential Method (Lecture 14, Example 5)
Analyze a sequence of
Click to see the solution
Key Concept: The number of elements in the stack is exactly the amount of prepaid removal work.
Let
The stack starts empty, so
For
For
For
be the number of elements actually removed. The actual cost is
All three amortized costs are at most
Answer: With
4.6. Analyze Binary Counter by the Potential Method (Lecture 14, Example 6)
Use the potential method to analyze INCREMENT on a binary counter stored as a bit array.
Click to see the solution
Key Concept: The
Let
The initial all-zero counter has potential
Suppose an increment changes
Let the old number of
The potential change is therefore
Now compute the amortized cost:
If the counter overflows because all bits are
Answer: With potential equal to the number of
4.7. Analyze Dynamic Array Expansion (Lecture 14, Example 7)
Consider a dynamic array that supports AddLast. When the array is full, the capacity doubles and all existing elements are copied. Analyze AddLast using the potential method.
Click to see the solution
Key Concept: Ordinary appends build up potential that pays for the next resize.
Let
Assume the table is initialized and resized so that the potential is nonnegative in the states under consideration. This is the standard expansion-only setting where the table is at least half full after the initial small cases.
There are two cases.
Case 1: no resize. Before the operation, the table has
Thus
Case 2: resize. Before the operation, the table is full:
The new potential is
The old potential is
Therefore
Both cases have amortized cost
Answer: With AddLast has amortized cost
4.8. Implement a Queue with Two Stacks (Lecture 14, Example 8)
Implement a queue using two stacks so that Enqueue and Dequeue have
Click to see the solution
Key Concept: Each element is pushed onto the input stack once, transferred once, and popped from the output stack once.
Use two stacks:
receives newly enqueued elements; supplies elements for dequeue.
The operations are:
ENQUEUE(x)
1 R.push(x)
DEQUEUE()
1 if F is empty
2 while R is not empty
3 F.push(R.pop())
4 return F.pop()
The transfer reverses the order of
Now assign amortized costs:
| Operation part | Actual cost | Amortized charge |
|---|---|---|
push into Enqueue |
||
| move one element |
paid by stored credit | |
pop from Dequeue |
A single enqueue is charged
Finally, the actual pop from
Each element is transferred at most once, because after it moves from
Answer: Use one input stack and one output stack; charge enqueue
4.9. Analyze Dynamic Table with Expansion and Contraction (Lecture 14, Example 9)
Consider a dynamic array supporting AddLast and RemoveLast. When full, the table doubles in size; when the number of elements drops below one quarter of the capacity, the table halves in size. Analyze the operations using the potential method.
Click to see the solution
Key Concept: The potential must pay for both copying during expansion and copying during contraction.
Let
This function is always nonnegative in the allowed range. It is zero at
For ordinary operations that do not resize,
Now check expansion. Just before expansion,
The operation copies
Thus
Now check contraction. Contraction happens after a removal makes the size drop below
Before contraction, the table is in the lower branch, so the potential is approximately
When
Therefore the expensive contraction is paid by the potential accumulated while the table was becoming sparse.
Answer: The piecewise potential above gives constant amortized cost for ordinary operations and pays for both resizing directions, so AddLast and RemoveLast are
4.10. Analyze Union by Smaller Set (Lecture 14, Example 10)
Consider a data structure storing a universe of elements and supporting
Click to see the solution
Key Concept: Whenever an element is moved, the size of its containing set at least doubles.
Implement union by moving or relabeling every element of the smaller set into the larger set. The cost of
is proportional to
Track one fixed element
Suppose
So every time
The set size can never exceed
times.
There are
Since there can be at most
The same reasoning can be expressed as a potential argument by assigning each element remaining movement potential proportional to the number of future doublings still possible.
Answer: Moving the smaller set makes each element move at most Union is
4.11. Analyze Periodic Rebalancing of a Binary Search Tree (Lecture 14, Example 11)
Consider a binary search tree supporting Insert(x). After every Insert using the accounting method and show
Click to see the solution
Key Concept: Each insertion deposits credit toward the next rebuild, and rebuilding restores logarithmic height.
After a full rebalance, a binary search tree with
Let this height be
Now pay for the rebuild. A full rebalance costs
Over a phase of sufficiently many insertions, this accumulates enough credit to pay for global rebuilding. The intended amortized-accounting picture is:
- Each insertion pays its own search and link cost,
. - Each insertion also deposits
credit. - The saved credits are spent when the next full rebalance occurs.
Thus every insertion is charged
amortized cost.
One subtle point is that the exact trigger rule must guarantee enough insertions between rebuilds to fund an
Answer: Charge each insertion